package bhwz.seac3.db;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
//import org.hibernate.tool.hbm2ddl.SchemaExport;

public class Database {
	private static SessionFactory buildSessionFactory() {
			try {
				// Create the SessionFactory from hibernate.cfg.xml
				Configuration cfg = new Configuration().configure();
				//SchemaExport export=new SchemaExport(cfg);
		        //export.create(true,true);
				return cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
						.applySettings(cfg.getProperties())
						.build());
			} catch (Throwable ex) {
				// Make sure you log the exception, as it might be swallowed
				System.err.println("Initial SessionFactory creation failed."
						+ ex);
				throw new ExceptionInInitializerError(ex);
			}
		}

	private static SessionFactory sessionFactory = buildSessionFactory();

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static Session getSession() {
		return sessionFactory.openSession();
	}
	
	public static interface Transaction{
		public void execute(Session session);
	}
	
	/**
	 * execute the functional interface as a transaction<br><br>
	 * if you want this function returns a value,use like this:<br>
	 * Object[] returnValue=new Object[1];<br>
	 * executeTransaction(s->(returnValue[0]="someObject"));<br>
	 * System.out.println(returnValue[0]);<br> 
	 * 
	 * @param transaction a functional interface<br>
	 * eg: (org.hibernate.Session s) -> {...}
	 * @throws Exception
	 */
	public static void executeTransaction(Transaction transaction)throws Exception{
		Session session=null;
		Exception exception=null;
		try{
			session=getSession();
			session.beginTransaction();
			transaction.execute(session);
			session.getTransaction().commit();
		}catch(Exception e){
			session.getTransaction().rollback();
			exception=e;
		}finally{
			session.close();
		}
		if(exception!=null){
			throw exception;
		}
	}
	
}